package com.zzy.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import weibo4j.Timeline;
import weibo4j.Weibo;
import weibo4j.http.ImageItem;
import weibo4j.model.PostParameter;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.WeiboException;
import weibo4j.util.WeiboConfig;

/**
 * 将某个用户的微博
 * 同步到我的微博中
 * @author eason
 *
 */
public class CopyWeibo {

	public static void main(String[] args) throws IOException {
		String access_token = "2.008iGhsCgrdWgDebec65d6c60B_qJ8";
		Weibo weibo = new Weibo();
		weibo.setToken(access_token);
		
		Timeline tm = new Timeline();
		try {
			StatusWapper statusWapper = tm.getUserTimelineByName("MIUI_ROM");
			List<Status> status = statusWapper.getStatuses();
			ExecutorService service = Executors.newSingleThreadExecutor();
			BlockingQueue queue = new ArrayBlockingQueue(status.size(), true, status);
			service.execute(new CopyThread(queue));
		} catch (WeiboException e) {
			e.printStackTrace();
		} 
	}
	
	public static byte[] readFileImageFromUrl(String urlPath)throws IOException{
		URL url = new URL(urlPath); 
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		InputStream is = conn.getInputStream();
		byte[] bytes = readInputStream(is);
		return bytes;
	}
	
	public static byte[] readInputStream(InputStream is) { 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        byte[] buffer = new byte[1024]; 
        int length = -1; 
        try { 
            while ((length = is.read(buffer)) != -1) { 
                baos.write(buffer, 0, length); 
            } 
            baos.flush(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        byte[] data = baos.toByteArray(); 
        try { 
            is.close(); 
            baos.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return data; 
    }

}


class CopyThread extends Thread {
	
	private BlockingQueue queue;
	
	public CopyThread(BlockingQueue queue) {
		this.queue = queue;
	}
	
	public void run() {
		try {
			while(true) {
				Status status = (Status) queue.poll();
				if(status != null) {
					byte[] content = readFileImageFromUrl(status.getOriginalPic());
					ImageItem pic = new ImageItem("pic",content);
					new Status(new Weibo().client.multPartURL(
							WeiboConfig.getValue("baseURL") + "statuses/upload.json",
							new PostParameter[] { 
									new PostParameter("status", java.net.URLEncoder.encode(status.getText(),"utf-8")),
									new PostParameter("lat", status.getLatitude()),
									new PostParameter("long", status.getLongitude()),
									new PostParameter("annotations", status.getAnnotations()) }, pic));
					System.out.println("SUCESS!" + status.getText());
					System.out.println(Thread.currentThread());
					try {
						this.sleep(1000 * 10L);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else{
					this.sleep(1000 * 60L * 3);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WeiboException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	public static byte[] readFileImageFromUrl(String urlPath)throws IOException{
		URL url = new URL(urlPath); 
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		InputStream is = conn.getInputStream();
		byte[] bytes = readInputStream(is);
		return bytes;
	}
	
	public static byte[] readInputStream(InputStream is) { 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        byte[] buffer = new byte[1024]; 
        int length = -1; 
        try { 
            while ((length = is.read(buffer)) != -1) { 
                baos.write(buffer, 0, length); 
            } 
            baos.flush(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        byte[] data = baos.toByteArray(); 
        try { 
            is.close(); 
            baos.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return data; 
    }

}